package rstplus;

/*
 * RST - Russian SMS transliterator
 * Copyleft 2011
 * Author: Alexey Shat'ko (Алексей Шатько), rstapp@yandex.ru
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this source code (in file copying.txt); if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */


import java.io.*;
import java.util.Enumeration;
import java.util.Vector;
import javax.microedition.rms.*;

public final class PhonebookStorage {

    private static final String RS_NAME = "rstplus.pb";
    private static RecordStore rs = null;
    private static int rsOpen = 0;

    private static void rsOpen() throws RecordStoreException {
        if (rsOpen <= 0) {
            rs = RecordStore.openRecordStore(RS_NAME, true);
            rsOpen = 1;
        } else {
            rsOpen++;
        }
    }

    private static void rsClose() throws RecordStoreException {
        if (rsOpen > 1) {
            rsOpen--;
        } else if (rsOpen == 1) {
            rs.closeRecordStore();
            rs = null;
            rsOpen = 0;
        }
    }
    
    private static boolean enabled;
    private static Vector items = null;

    public static void sort() {
        if (items != null) {
            int len = items.size();
            for (int i = 0; i < len - 1; i++) {
                int k = i;
                PhonebookItem ii = (PhonebookItem) items.elementAt(i);
                PhonebookItem ki = ii;
                for (int j = i + 1; j < len; j++) {
                    PhonebookItem ji = (PhonebookItem) items.elementAt(j);
                    if (ji.getName().compareTo(ki.getName()) < 0) {
                        k = j;
                        ki = ji;
                    }
                }
                if (i != k) {
                    items.setElementAt(ki, i);
                    items.setElementAt(ii, k);
                }
            }
        }
    }

    public static void load() throws RecordStoreException {
        if (!enabled) {
            throw new RuntimeException();
        }
        rsOpen();
        try {
            items = new Vector();
            RecordEnumeration re = rs.enumerateRecords(null, null, false);
            try {
                while (re.hasNextElement()) {
                    int id = re.nextRecordId();
                    byte[] record = rs.getRecord(id);
                    PhonebookItem item = new PhonebookItem(record);
                    items.addElement(item);
                }
            } finally {
                re.destroy();
            }
        } finally {
            rsClose();
        }
        sort();
    }

    public static int getItemsCount() {
        return items.size();
    }

    public static PhonebookItem getItem(int index) {
        return (PhonebookItem) items.elementAt(index);
    }

    public static void deleteItem(int index) {
        items.removeElementAt(index);
    }

    public static void addItem(String name, String number) {
        items.addElement(new PhonebookItem(name, number));
    }

    public static void save() throws RecordStoreException {
        if (!enabled) {
            throw new RuntimeException();
        }
        rsOpen();
        try {
            Vector ids = new Vector();
            RecordEnumeration re = rs.enumerateRecords(null, null, false);
            try {
                while (re.hasNextElement()) {
                    ids.addElement(new Integer(re.nextRecordId()));
                }
            } finally {
                re.destroy();
            }
            Enumeration e = ids.elements();
            while (e.hasMoreElements()) {
                int id = ((Integer) e.nextElement()).intValue();
                rs.deleteRecord(id);
            }
            Enumeration itemsE = items.elements();
            while (itemsE.hasMoreElements()) {
                PhonebookItem item = (PhonebookItem) itemsE.nextElement();
                byte[] record = item.toByByteArray();
                rs.addRecord(record, 0, record.length);
            }
        } finally {
            rsClose();
        }
    }

    public static void unload() {
        items = null;
    }

    public static void setEnabled(boolean _enabled) {
        boolean oldEnabled = enabled;
        enabled = _enabled;
        if (oldEnabled && !enabled) {
            try {
                rsOpen = 0;
                if (rs != null) {
                    try {
                        rs.closeRecordStore();
                    } catch (Exception exc) {
                        //Skip
                    }
                }
                RecordStore.deleteRecordStore(RS_NAME);
            } catch (Exception exc) {
                //Skip
            }
        }
    }

    public static boolean isEnabled() {
        return enabled;
    }

    public static final class PhonebookItem {

        private String name;
        private String number;

        public PhonebookItem(String name, String number) {
            if ((name.length() == 0) || !SMSSender.checkNumber(number)) {
                throw new IllegalArgumentException();
            }
            this.name = name;
            this.number = number;
        }

        public PhonebookItem(byte[] data) {
            try {
                DataInputStream stream = new DataInputStream(new ByteArrayInputStream(data));
                try {
                    setName(stream.readUTF());
                    setNumber(stream.readUTF());
                } finally {
                    stream.close();
                }
            } catch (IOException exc) {
                throw new RuntimeException();
            }
        }

        public byte[] toByByteArray() {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                DataOutputStream dos = new DataOutputStream(baos);
                try {
                    dos.writeUTF(name);
                    dos.writeUTF(number);
                } finally {
                    dos.close();
                }
            } catch (IOException exc) {
                throw new RuntimeException();
            }
            return baos.toByteArray();
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            if (name.length() == 0) {
                throw new IllegalArgumentException();
            }
            this.name = name;
        }

        public String getNumber() {
            return number;
        }

        public void setNumber(String number) {
            if (!SMSSender.checkNumber(number)) {
                throw new IllegalArgumentException();
            }
            this.number = number;
        }
    }
}
